package ai.people.platform.archives.ws.executor;

import ai.people.netmon.framework.domain.archives.request.InformationSearchRequest;
import ai.people.netmon.framework.domain.websocket.vo.WebSocketReqVO;
import ai.people.netmon.framework.exception.enums.ParamExceptionEnum;
import ai.people.netmon.framework.exception.type.BusinessException;
import ai.people.netmon.framework.utils.AssertUtils;
import ai.people.platform.archives.service.InformationSearchService;
import ai.people.platform.archives.ws.context.WsExecutorContext;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.websocket.Session;

/**
 * @author LiGuanNan
 * @date 2022/7/7 10:24
 */
@Service
public class InformationSearchWsExecutor implements WebSocketExecutor {
    @Autowired
    private InformationSearchService informationSearchService;

    @PostConstruct
    public void init(){
        WsExecutorContext.addWebSocketExecutor("information-search", this);
    }

    /**
     * 连接成功
     *
     * @param session
     */
    @Override
    public void onOpen(Session session) {

    }

    /**
     * 连接关闭
     *
     * @param session
     */
    @Override
    public void onClose(Session session) {

    }

    /**
     * 接收到消息
     *
     * @param text
     * @param session
     */
    @Override
    public String onMsg(String text, Session session) {
        WebSocketReqVO<InformationSearchRequest> reqParam = null;
        try {
            reqParam = JSONObject.parseObject(text, new TypeReference<>() {});
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException(ParamExceptionEnum.PARAMETER_PARSING_EXCEPTION);
        }
        AssertUtils.isTrue(reqParam != null && reqParam.getData() != null, ParamExceptionEnum.INSUFFICIENT_PARAMETERS);
        return informationSearchService.wsSearch(reqParam.getData(), reqParam.getMsgType(), session) + "";
    }

    /**
     * 接收到消息
     *
     * @param text
     * @param session
     */
    @Override
    public String sendMsg(String text, Session session) {
        return null;
    }
}
